import React, { useState, useEffect, useRef } from 'react';
import { Table, Button, Space, Input, DatePicker, Breadcrumb, Select, Card, Radio, Upload, Switch, Modal, Tag, Checkbox } from 'antd';
import { SearchOutlined, LeftOutlined, PlusOutlined, CloseOutlined, UpOutlined, DownOutlined } from '@ant-design/icons';
import styles from './ProductList.module.css';
import '@wangeditor/editor/dist/css/style.css';
import { createEditor, createToolbar } from '@wangeditor/editor'
import { _apiProductList } from '../../../api';

function ProductList() {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [isAddingProduct, setIsAddingProduct] = useState(false);
  const [selectedFirstCategory, setSelectedFirstCategory] = useState('');
  const [selectedSecondCategory, setSelectedSecondCategory] = useState('');
  const [step, setStep] = useState(1);
  const [form, setForm] = useState({
    isOnShelf: false,      // 是否上架
    isRecommend: false,   // 是否分销
    merchantId: '',       // 所属商户
    productCategory: '',  // 商品类别
    storeCategory: '',   // 店铺类目
    tags: [],            // 标签属性
    brand: '',           // 选择品牌
    productTitle: '',    // 商品标题
    subtitle: '',        // 副标题
    unit: '件',          // 计件单位
    sortNum: '99',       // 排序数字
    productName: '',
    keywords: '',
    price: '',
    supportDoorService: true,
    description: '',
    images: [],
    selectedSpec: ''
  });
  const [editor, setEditor] = useState(null);
  const [editorHtml, setEditorHtml] = useState('');
  const editorRef = useRef(null);
  const [loading, setLoading] = useState(false);
  const [productList, setProductList] = useState([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [activeTab, setActiveTab] = useState('basic'); // basic, price, photos, description
  const [merchantModalVisible, setMerchantModalVisible] = useState(false);
  const [selectedMerchant, setSelectedMerchant] = useState(null);
  const [merchantList, setMerchantList] = useState([]);
  const [searchKeyword, setSearchKeyword] = useState('');
  const [categoryModalVisible, setCategoryModalVisible] = useState(false);
  const [selectedCategories, setSelectedCategories] = useState([]);
  const [expandedCategory, setExpandedCategory] = useState('洗鞋'); // 默认展开洗鞋
  const categoryPopoverRef = useRef(null);

  // 编辑器配置
  const editorConfig = {
    placeholder: '请输入内容...',
  };

  // 工具栏配置
  const toolbarConfig = {};

  // 修改编辑器初始化和销毁逻辑
  useEffect(() => {
    if (step !== 2) {
      // 当离开第二步时，清理编辑器
      if (editorRef.current) {
        editorRef.current.destroy();
        editorRef.current = null;
        setEditor(null);
      }
      return;
    }

    // 确保DOM元素存在
    const editorContainer = document.getElementById('editor-container');
    const toolbarContainer = document.getElementById('toolbar-container');
    
    if (!editorContainer || !toolbarContainer) return;

    // 初始化编辑器
    const initEditor = () => {
      if (editorRef.current) return;

      const editorInstance = createEditor({
        selector: '#editor-container',
        html: editorHtml,
        config: editorConfig,
      });
      
      const toolbarInstance = createToolbar({
        editor: editorInstance,
        selector: '#toolbar-container',
        config: toolbarConfig,
      });

      editorRef.current = editorInstance;
      setEditor(editorInstance);

      // 监听内容变化
      editorInstance.on('change', () => {
        setEditorHtml(editorInstance.getHtml());
      });
    };

    // 延迟初始化以确保DOM已经渲染
    const timer = setTimeout(initEditor, 100);

    return () => {
      clearTimeout(timer);
      if (editorRef.current) {
        editorRef.current.destroy();
        editorRef.current = null;
        setEditor(null);
      }
    };
  }, [step]);

  const columns = [
    {
      title: '商品编号',
      dataIndex: 'goodsNo',
      key: 'goodsNo',
      align: 'center',
    },
    {
      title: '商品名称',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      render: (text, record) => (
        <div style={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: '12px',
          justifyContent: 'center',
          width: '100%'
        }}>
          <div style={{
            width: '50px',
            height: '50px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center'
          }}>
            <img 
              src={record.imgUrl} 
              alt={text}
              style={{ 
                maxWidth: '100%',
                maxHeight: '100%',
                objectFit: 'contain',
                borderRadius: '4px'
                
              }} 
            />
          </div>
          <span>{text}</span>
        </div>
      )
    },
    {
      title: '价格（元）',
      dataIndex: 'sellPrice',
      key: 'sellPrice',
      align: 'center',
      render: (text) => text ? `¥${text}` : '-'
    },
    {
      title: '上架时间',
      dataIndex: 'upTime',
      key: 'upTime',
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (_, record) => (
        <Space size="middle">
          <Button type="link">删除</Button>
          <Button type="link">编辑</Button>
        </Space>
      ),
    },
  ];

  // 分类数据
  const firstCategories = [
    { value: 'wash', label: '洗鞋' },
    { value: 'care', label: '护理鞋' },
    { value: 'repair', label: '修鞋' },
  ];

  const secondCategories = {
    wash: [
      { value: 'leather', label: '皮鞋护理' },
      { value: 'sports', label: '运动鞋护理' },
      { value: 'canvas', label: '帆布鞋护理' },
      { value: 'brand', label: '名牌鞋护理' },
    ]
  };

  const onSelectChange = (newSelectedRowKeys) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  const handleAddProduct = () => {
    setIsAddingProduct(true);
    setActiveTab('basic');  // 确保每次点击新增都显示第一个 tab
  };

  const handleNext = () => {
    setStep(2);
  };

  const handleBack = () => {
    if (step === 2) {
      // 从第二步返回第一步
      if (editorRef.current) {
        editorRef.current.destroy();
        editorRef.current = null;
        setEditor(null);
      }
      setStep(1);
    } else {
      // 从第一步返回列表页
      setIsAddingProduct(false);
      setSelectedFirstCategory('');
      setSelectedSecondCategory('');
      setStep(1);
    }
  };

  // 在组件顶部添加一个获取分类显示文本的函数
  const getCategoryText = () => {
    if (!selectedFirstCategory || !selectedSecondCategory) return '';
    
    const firstCategory = firstCategories.find(c => c.value === selectedFirstCategory);
    const secondCategory = secondCategories[selectedFirstCategory]?.find(c => c.value === selectedSecondCategory);
    
    if (firstCategory && secondCategory) {
      return `${firstCategory.label} - ${secondCategory.label}`;
    }
    return '';
  };

  // 获取商品列表数据
  const fetchProductList = async (params = {}) => {
    try {
      setLoading(true);
      const { current = 1, pageSize = 10 } = params;
      const response = await _apiProductList({
        page: current,
        pageSize,
        ...params
      });
      
      // 处理返回的数据
      const formattedList = response.data.map(item => ({
        ...item,
        key: item.id // 为每条数据添加唯一key
      }));
      
      setProductList(formattedList);
      setPagination({
        ...pagination,
        current,
        pageSize,
        total: response.total || 0  // 根据实际接口返回格式调整
      });
    } catch (error) {
      console.error('获取商品列表失败：', error);
    } finally {
      setLoading(false);
    }
  };

  // 首次加载和分页变化时获取数据
  useEffect(() => {
    fetchProductList();
  }, []);

  // 修改表格分页处理函数
  const handleTableChange = (pagination, filters, sorter) => {
    fetchProductList({
      current: pagination.current,
      pageSize: pagination.pageSize,
      // 可以添加其他查询参数
    });
  };

  // 修改表格列定义
  const merchantColumns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      align: 'left',
      width: '15%',
    },
    {
      title: '店铺名称',
      dataIndex: 'shopName',
      key: 'shopName',
      align: 'left',
      width: '25%',
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      align: 'center',
      width: '15%',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      width: '15%',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: '10%',
      render: (status) => (
        <Tag color={status === '正常' ? 'success' : 'error'} className={styles.statusTag}>
          {status}
        </Tag>
      ),
    },
    {
      title: '成立时间',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'center',
      width: '20%',
    },
  ];

  // 修改商户选择模态框组件
  const MerchantSelectModal = () => (
    <Modal
      title="选择商户"
      open={merchantModalVisible}
      onCancel={() => setMerchantModalVisible(false)}
      footer={null}
      width={1200}
      className={styles.merchantModal}
    >
      <div className={styles.merchantModalContent}>
        <Input.Search
          placeholder="输入关键字"
          onSearch={(value) => setSearchKeyword(value)}
          style={{ marginBottom: 16 }}
          className={styles.searchInput}
        />
        <Table
          columns={merchantColumns}
          dataSource={merchantList}
          rowKey="id"
          className={styles.merchantTable}
          pagination={{
            total: merchantList.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条`,
            className: styles.pagination
          }}
          onRow={(record) => ({
            onClick: () => {
              setSelectedMerchant(record);
              setMerchantModalVisible(false);
            },
          })}
        />
      </div>
    </Modal>
  );

  // 添加模拟数据
  const mockMerchantList = [
    {
      id: '1',
      username: 'dtnds',
      shopName: '绿鑫园三菱鞋馆',
      category: '洗护用品',
      type: '微小商户',
      status: '正常',
      createTime: '2024-09-15 00:58:15'
    },
    {
      id: '2',
      username: 'test',
      shopName: '绿鑫洗护用品店',
      category: '洗护用品',
      type: '工商个体户',
      status: '正常',
      createTime: '2024-09-08 15:03:27'
    },
    {
      id: '3',
      username: 'merchant3',
      shopName: '优品洗护中心',
      category: '洗护用品',
      type: '微小商户',
      status: '正常',
      createTime: '2024-09-07 09:15:33'
    },
    {
      id: '4',
      username: 'merchant4',
      shopName: '洁净鞋业护理',
      category: '洗护用品',
      type: '工商个体户',
      status: '正常',
      createTime: '2024-09-06 14:22:45'
    }
  ];

  // 在组件内添加 useEffect 来设置模拟数据
  useEffect(() => {
    setMerchantList(mockMerchantList);
  }, []);

  // 修改商品类别数据结构
  const categoryOptions = {
    洗鞋: {
      subCategories: [
        '儿童鞋',
        '运动鞋',
        '休闲鞋',
        '皮鞋靴子',
        '奢侈品',
        '雪地靴',
        '磨砂鞋',
        '绒面鞋',
        '鞋子除臭'
      ]
    },
    保养: {
      subCategories: []
    }
  };

  // 修改类别选择的弹出层组件
  const CategorySelectPopover = () => {
    const [checkedItems, setCheckedItems] = useState(selectedCategories);
    const [expandedCategory, setExpandedCategory] = useState('洗鞋'); // 默认展开洗鞋

    const handleMainCategoryChange = (category, checked) => {
      let newCheckedItems = [...checkedItems];
      if (checked) {
        // 当选中主类别时，直接添加主类别名称
        newCheckedItems.push(category);
      } else {
        // 取消选中时，只移除主类别，保留子类别
        newCheckedItems = newCheckedItems.filter(item => item !== category);
      }
      setCheckedItems(newCheckedItems);
      setSelectedCategories(newCheckedItems);
    };

    const handleSubCategoryChange = (category, subCategory, checked) => {
      let newCheckedItems = [...checkedItems];
      const fullCategory = `${category}-${subCategory}`;
      if (checked) {
        newCheckedItems.push(fullCategory);
      } else {
        newCheckedItems = newCheckedItems.filter(item => item !== fullCategory);
      }
      setCheckedItems(newCheckedItems);
      setSelectedCategories(newCheckedItems);
    };

    // 添加一个函数来检查主类别是否应该显示为选中状态
    const isMainCategoryChecked = (category) => {
      // 如果主类别直接被选中，或者所有子类别都被选中，则显示为选中状态
      const directlyChecked = checkedItems.includes(category);
      if (directlyChecked) return true;

      const subCategories = categoryOptions[category].subCategories;
      if (subCategories.length === 0) return false;

      const selectedSubCategories = checkedItems.filter(item => 
        item.startsWith(`${category}-`)
      ).length;

      return selectedSubCategories === subCategories.length;
    };

    return (
      <div className={styles.categoryPopover}>
        {Object.entries(categoryOptions).map(([category, { subCategories }]) => (
          <div key={category} className={styles.categoryGroup}>
            <div className={styles.mainCategory}>
              <Checkbox
                checked={isMainCategoryChecked(category)}
                onChange={(e) => handleMainCategoryChange(category, e.target.checked)}
              >
                {category}
              </Checkbox>
              {subCategories.length > 0 && (
                <span 
                  onClick={() => setExpandedCategory(expandedCategory === category ? null : category)}
                  className={styles.expandIcon}
                >
                  {expandedCategory === category ? <UpOutlined /> : <DownOutlined />}
                </span>
              )}
            </div>
            {subCategories.length > 0 && expandedCategory === category && (
              <div className={styles.subCategories}>
                {subCategories.map(subCategory => (
                  <Checkbox
                    key={subCategory}
                    checked={checkedItems.includes(`${category}-${subCategory}`)}
                    onChange={(e) => handleSubCategoryChange(category, subCategory, e.target.checked)}
                  >
                    {subCategory}
                  </Checkbox>
                ))}
              </div>
            )}
          </div>
        ))}
      </div>
    );
  };

  // 添加点击外部关闭的事件处理
  useEffect(() => {
    const handleClickOutside = (event) => {
      if (categoryPopoverRef.current && 
          !categoryPopoverRef.current.contains(event.target) &&
          !event.target.closest('.ant-btn')) {  // 排除点击"+"按钮的情况
        setCategoryModalVisible(false);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  if (isAddingProduct) {
    return (
      <div className={styles.container}>
        <div className={styles.breadcrumb}>
          <div className={styles.locationWrapper}>
            <div className={styles.currentLocation}>
              当前位置：商品管理 &gt; 添加商品
            </div>
            <Button 
              icon={<LeftOutlined />}
              onClick={handleBack}
              className={styles.backButton}
            >
              返回
            </Button>
          </div>
        </div>

        <div className={styles.contentSection}>
          <div className={styles.tabs}>
            <div 
              className={`${styles.tab} ${activeTab === 'basic' ? styles.active : ''}`}
              onClick={() => setActiveTab('basic')}
            >
              基本信息
            </div>
            <div 
              className={`${styles.tab} ${activeTab === 'price' ? styles.active : ''}`}
              onClick={() => setActiveTab('price')}
            >
              商品价格
            </div>
            <div 
              className={`${styles.tab} ${activeTab === 'photos' ? styles.active : ''}`}
              onClick={() => setActiveTab('photos')}
            >
              商品相册
            </div>
            <div 
              className={`${styles.tab} ${activeTab === 'description' ? styles.active : ''}`}
              onClick={() => setActiveTab('description')}
            >
              商品介绍
            </div>
          </div>

          {activeTab === 'basic' && (
            <div className={styles.formContent}>
              <div className={styles.formItem}>
                <span className={styles.label}>是否上架</span>
                <Switch 
                  checked={form.isOnShelf}
                  onChange={(checked) => setForm({...form, isOnShelf: checked})}
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}>是否分销</span>
                <Switch 
                  checked={form.isRecommend}
                  onChange={(checked) => setForm({...form, isRecommend: checked})}
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label} required>所属商户</span>
                <div className={styles.merchantSelector}>
                  {selectedMerchant ? (
                    <div className={styles.selectedMerchantTag}>
                      {selectedMerchant.shopName}
                      <CloseOutlined onClick={(e) => {
                        e.stopPropagation();
                        setSelectedMerchant(null);
                      }} />
                    </div>
                  ) : (
                    <Button 
                      onClick={() => setMerchantModalVisible(true)}
                      icon={<PlusOutlined />}
                    >
                      请选择
                    </Button>
                  )}
                </div>
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}>商品类别</span>
                <div className={styles.categorySelector}>
                  <div className={styles.selectedCategories}>
                    {selectedCategories.map(category => {
                      // 如果不包含 "-" 说明是主类别
                      if (!category.includes('-')) {
                        return (
                          <Tag 
                            key={category}
                            closable
                            onClose={() => {
                              setSelectedCategories(selectedCategories.filter(c => c !== category));
                            }}
                            className={styles.categoryTag}
                          >
                            {category}
                          </Tag>
                        );
                      }
                      // 处理子类别
                      const [_, sub] = category.split('-');
                      return (
                        <Tag 
                          key={category}
                          closable
                          onClose={() => {
                            setSelectedCategories(selectedCategories.filter(c => c !== category));
                          }}
                          className={styles.categoryTag}
                        >
                          {sub}
                        </Tag>
                      );
                    })}
                    <Button
                      icon={<PlusOutlined />}
                      onClick={() => setCategoryModalVisible(true)}
                      size="small"
                    />
                  </div>
                  {categoryModalVisible && (
                    <div 
                      ref={categoryPopoverRef}
                      className={styles.categoryPopoverWrapper}
                    >
                      <CategorySelectPopover />
                    </div>
                  )}
                </div>
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}>店铺类目</span>
                <Select
                  value={form.storeCategory}
                  onChange={(value) => setForm({...form, storeCategory: value})}
                  placeholder="请选择"
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}>标签属性</span>
                <Select
                  value={form.tags}
                  onChange={(value) => setForm({...form, tags: value})}
                  placeholder="请选择"
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}><span className={styles.required}></span>选择品牌</span>
                <Select
                  value={form.brand}
                  onChange={(value) => setForm({...form, brand: value})}
                  placeholder="请选择"
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}><span className={styles.required}></span>商品标题</span>
                <Input 
                  value={form.productTitle}
                  onChange={(e) => setForm({...form, productTitle: e.target.value})}
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}>副标题</span>
                <Input 
                  value={form.subtitle}
                  onChange={(e) => setForm({...form, subtitle: e.target.value})}
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}><span className={styles.required}></span>计件单位</span>
                <Input 
                  value={form.unit}
                  onChange={(e) => setForm({...form, unit: e.target.value})}
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}><span className={styles.required}></span>排序数字</span>
                <Input 
                  value={form.sortNum}
                  onChange={(e) => setForm({...form, sortNum: e.target.value})}
                />
              </div>
            </div>
          )}

          {activeTab === 'price' && (
            <div className={styles.formContent}>
              <div className={styles.formItem}>
                <span className={styles.label}>商品名称</span>
                <Input 
                  value={form.productName}
                  onChange={(e) => setForm({...form, productName: e.target.value})}
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}>关键词</span>
                <Input 
                  value={form.keywords}
                  onChange={(e) => setForm({...form, keywords: e.target.value})}
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}>商品售价</span>
                <Input 
                  value={form.price}
                  onChange={(e) => setForm({...form, price: e.target.value})}
                />
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}>是否支持上门服务</span>
                <Radio.Group
                  value={form.supportDoorService}
                  onChange={(e) => setForm({...form, supportDoorService: e.target.value})}
                >
                  <Radio value={true}>支持</Radio>
                  <Radio value={false}>不支持</Radio>
                </Radio.Group>
              </div>

              <div className={styles.formItem}>
                <span className={styles.label}>规格价格</span>
                <div className={styles.specPriceWrapper}>
                  <Select
                    style={{ width: 400 }}
                    placeholder="请选择已有规格"
                    value={form.selectedSpec}
                    onChange={(value) => setForm({...form, selectedSpec: value})}
                  >
                    {/* 这里可以添加规格选项 */}
                  </Select>
                  <Button 
                    type="primary" 
                    icon={<PlusOutlined />}
                    style={{ marginLeft: 8 }}
                  >
                    添加规格
                  </Button>
                </div>
              </div>
            </div>
          )}

          {activeTab === 'photos' && (
            <div className={styles.formContent}>
              <div className={styles.formItem}>
                <span className={styles.label}>图片上传</span>
                <Upload
                  listType="picture-card"
                  fileList={form.images}
                  onChange={({fileList}) => setForm({...form, images: fileList})}
                >
                  <div>
                    <PlusOutlined />
                    <div style={{ marginTop: 8 }}>上传照片</div>
                  </div>
                </Upload>
              </div>
            </div>
          )}

          {activeTab === 'description' && (
            <div className={styles.formContent}>
              <div className={styles.formItem}>
                <span className={styles.label}>商品详情</span>
                <div className={styles.editorWrapper}>
                  <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
                    <div id="toolbar-container" style={{ borderBottom: '1px solid #ccc' }}></div>
                    <div 
                      id="editor-container" 
                      style={{ height: '400px', overflowY: 'hidden' }}
                    ></div>
                  </div>
                </div>
              </div>
            </div>
          )}

          <div className={styles.formActions}>
            <Button type="primary" onClick={() => console.log('保存')}>确认保存</Button>
            <Button onClick={handleBack}>返回上一页</Button>
          </div>
        </div>

        <MerchantSelectModal />
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <div className={styles.breadcrumb}>
        <Breadcrumb>
          <Breadcrumb.Item>商品管理</Breadcrumb.Item>
          <Breadcrumb.Item>商品列表</Breadcrumb.Item>
        </Breadcrumb>
      </div>

      <div className={styles.operationTips}>
        <ol>
          <li>该页面展示了商城所有的商品信息，可对商品进行编辑修改操作。</li>
          <li>添加商品后，不需要进行审核，可直接上架。</li>
        </ol>
      </div>

      <div className={styles.searchBar}>
        <Button type="primary" onClick={handleAddProduct}>+ 添加商品</Button>
        <Button danger>批量删除</Button>
        <Space>
          商品名称：
          <Input 
            placeholder="请输入" 
            className={styles.searchInput}
          />
        </Space>
        <Space>
          上架时间：
          <DatePicker 
            className={styles.datePicker} 
            placeholder="请输入"
          />
        </Space>
        <Button type="primary" icon={<SearchOutlined />}>
          查询
        </Button>
      </div>

      <Table 
        rowSelection={rowSelection}
        columns={columns}
        dataSource={productList}
        pagination={pagination}
        loading={loading}
        onChange={handleTableChange}
      />
    </div>
  );
}

export default ProductList;